package com.xyz.service.impl;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xyz.config.SystemData;
import com.xyz.dao.mapper.BusinessFileDaoMapper;
import com.xyz.dao.pojo.BusinessFileVo;
import com.xyz.dto.EquipmentDto;
import com.xyz.dto.EquipmentElectricalDto;
import com.xyz.dto.enums.EnumBusinessType;
import com.xyz.dto.enums.EnumRepState;
import com.xyz.entity.mapper.*;
import com.xyz.entity.pojo.*;
import com.xyz.service.CommonService;
import com.xyz.service.EquipmentService;
import com.xyz.service.EquipmentTreeService;
import com.xyz.service.FileService;
import com.xyz.util.dto.DataResult;
import com.xyz.util.dto.GridData;
import com.xyz.util.dto.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class EquipmentServiceImpl implements EquipmentService {

    @Autowired
    private CommonService commonService;

    @Autowired
    private EquipmentInfoMapper equipmentInfoMapper;

    @Autowired
    private EquipmentTreeMapper equipmentTreeMapper;

    @Autowired
    private EquipmentPlcConfigMapper equipmentPlcConfigMapper;

    @Autowired
    private SystemEmployeeMapper systemEmployeeMapper;

    @Autowired
    private SystemFileMapper systemFileMapper;

    @Autowired
    private FileService fileService;

    @Autowired
    private BusinessFileMapper businessFileMapper;

    @Autowired
    private EquipmentOperationLogMapper equipmentOperationLogMapper;

    @Autowired
    private EquipmentMoveLogMapper equipmentMoveLogMapper;

    @Autowired
    private UpkeepWorkOrderMapper upkeepWorkOrderMapper;

    @Autowired
    private PatrolWorkOrderMapper patrolWorkOrderMapper;

    @Autowired
    private EquipmentElectricalMapper equipmentElectricalMapper;

    @Autowired
    private EquipmentTreeService equipmentTreeService;

    @Autowired
    private UpkeepTaskMapper upkeepTaskMapper;

    @Autowired
    private BusinessFileDaoMapper businessFileDao;

    @Autowired
    private UpkeepMaintenanceMapper upkeepMaintenanceMapper;

    @Override
    public DataResult selectEquipmentTree(LoginInfo li) throws Exception {
        List<Map<String, Object>> list = new ArrayList<>();

        List<EquipmentTree> etOneList = new ArrayList<>();
        List<EquipmentTree> etTwoList = new ArrayList<>();
        List<EquipmentTree> etThreeList = new ArrayList<>();

        EquipmentTreeExample etExample = new EquipmentTreeExample();
        etExample.createCriteria().andTypeLessThan(3).andIsDeleteEqualTo(0);
        etExample.setOrderByClause("sort");
        List<EquipmentTree> etList = equipmentTreeMapper.selectByExample(etExample);
        for (EquipmentTree et : etList) {
            if (et.getType() == 0) {
                etOneList.add(et);
            } else if (et.getType() == 1) {
                etTwoList.add(et);
            } else if (et.getType() == 2) {
                etThreeList.add(et);
            }
        }
        for (EquipmentTree etOne : etOneList) {
            Map<String, Object> oneMap = new HashMap<>();
            oneMap.put("id", etOne.getId());
            oneMap.put("name", etOne.getName());
            oneMap.put("sort", etOne.getSort());
            oneMap.put("code", etOne.getCode());
            List<Map<String, Object>> towList = new ArrayList<>();
            for (EquipmentTree etTwo : etTwoList) {
                if (etTwo.getBaseId().equals(etOne.getId())) {
                    Map<String, Object> twoMap = new HashMap<>();
                    twoMap.put("id", etTwo.getId());
                    twoMap.put("name", etTwo.getName());
                    twoMap.put("sort", etTwo.getSort());
                    twoMap.put("code", etTwo.getCode());
                    List<Map<String, Object>> threeList = new ArrayList<>();
                    for (EquipmentTree etThree : etThreeList) {
                        if (etThree.getBaseId().equals(etTwo.getId())) {
                            Map<String, Object> threeMap = new HashMap<>();
                            threeMap.put("id", etThree.getId());
                            threeMap.put("name", etThree.getName());
                            threeMap.put("sort", etThree.getSort());
                            threeMap.put("code", etThree.getCode());
                            threeMap.put("emType", etThree.getEmType());
                            threeList.add(threeMap);
                        }
                    }
                    twoMap.put("children", threeList);
                    towList.add(twoMap);
                }
            }
            oneMap.put("children", towList);
            list.add(oneMap);
        }
        return DataResult.build9100(list);
    }

    @Override
    public DataResult selectEquipmentTreeGroup(LoginInfo li, long id) throws Exception {
        List<Map<String, Object>> list = new ArrayList<>();

        EquipmentTreeExample etExample = new EquipmentTreeExample();
        etExample.createCriteria().andBaseIdEqualTo(id).andIsDeleteEqualTo(0);

        etExample.setOrderByClause("sort");
        List<EquipmentTree> etList = equipmentTreeMapper.selectByExample(etExample);
        for (EquipmentTree et : etList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", et.getId());
            map.put("name", et.getName());
            map.put("code", et.getCode());
            map.put("emType", et.getEmType());

            EquipmentInfoExample eiExample = new EquipmentInfoExample();
            eiExample.createCriteria().andEmTreeEqualTo(et.getId()).andIsDeleteEqualTo(0);
            eiExample.setOrderByClause("create_time desc");
            List<EquipmentInfo> eiList = equipmentInfoMapper.selectByExample(eiExample);
            List<Map<String, Object>> childrenList = new ArrayList<>();
            for (EquipmentInfo ei : eiList) {
                Map<String, Object> childrenMap = new HashMap<>();
                childrenMap.put("id", ei.getId());
                childrenMap.put("name", ei.getEmName());
                childrenMap.put("code", ei.getEmCode());
                childrenList.add(childrenMap);
            }

            map.put("children", childrenList);
            list.add(map);
        }

        EquipmentInfoExample eiExample = new EquipmentInfoExample();
        eiExample.createCriteria().andEmTreeEqualTo(id).andIsDeleteEqualTo(0);
        eiExample.setOrderByClause("create_time desc");
        List<EquipmentInfo> eiList = equipmentInfoMapper.selectByExample(eiExample);
        for (EquipmentInfo ei : eiList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", ei.getId());
            map.put("name", ei.getEmName());
            list.add(map);
        }

        return DataResult.build9100(list);
    }

    @Override
    public DataResult selectEquipmentTreeGroupNoEquipment(LoginInfo li, long id) throws Exception {
        List<Map<String, Object>> list = new ArrayList<>();
        EquipmentTreeExample etExample = new EquipmentTreeExample();
        etExample.createCriteria().andBaseIdEqualTo(id).andIsDeleteEqualTo(0);

        etExample.setOrderByClause("sort");
        List<EquipmentTree> etList = equipmentTreeMapper.selectByExample(etExample);
        for (EquipmentTree et : etList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", et.getId());
            map.put("name", et.getName());
            map.put("code", et.getCode());
            map.put("emType", et.getEmType());
            list.add(map);
        }
        return DataResult.build9100(list);
    }

    @Override
    public DataResult updateEquipmentTreeGroup(LoginInfo li, int type, long id, long baseTreeId) throws Exception {
        EquipmentTree baseEt = equipmentTreeMapper.selectByPrimaryKey(baseTreeId);
        if (type == 1) { // 拖拽设备组合
            if (baseEt.getType() != 2) {
                return DataResult.build9250("设备组合只能移动到子系统下");
            }
            EquipmentTree newEt = new EquipmentTree();
            newEt.setId(id);
            newEt.setBaseId(baseEt.getId());
            equipmentTreeMapper.updateByPrimaryKeySelective(newEt);
        } else {  // 拖拽设备
            if (baseEt.getType() != 2 && baseEt.getType() != 3) {
                return DataResult.build9250("设备只能移动到子系统或设备组合下");
            }
            EquipmentInfo newEi = new EquipmentInfo();
            newEi.setId(id);
            if (baseEt.getType() == 3) {
                newEi.setEmType(0);
            }
            newEi.setEmTree(baseTreeId);
            equipmentInfoMapper.updateByPrimaryKeySelective(newEi);
        }
        return DataResult.build9100();
    }

    @Override
    public DataResult insertEquipmentTreeGroupInfo(LoginInfo li, long baseId, String name, String code, int emType) throws Exception {
        EquipmentTreeExample etExample = new EquipmentTreeExample();
        etExample.createCriteria().andCodeEqualTo(code).andIsDeleteEqualTo(0);

        if (equipmentTreeMapper.countByExample(etExample) > 0) {
            return DataResult.build9250("设备组编码重复，新增失败");
        }
        EquipmentTree newEt = new EquipmentTree();
        newEt.setType(3);
        newEt.setBaseId(baseId);
        newEt.setName(name);
        newEt.setCode(code);
        newEt.setEmType(emType);
        newEt.setSort(0);
        newEt.setIsDelete(0);
        equipmentTreeMapper.insert(newEt);
        return DataResult.build9100();
    }

    @Override
    public DataResult updateEquipmentTreeGroupInfo(LoginInfo li, long id, String name, String code, int emType) throws Exception {
        EquipmentTreeExample etExample = new EquipmentTreeExample();
        etExample.createCriteria().andCodeEqualTo(code).andIdNotEqualTo(id).andIsDeleteEqualTo(0);

        if (equipmentTreeMapper.countByExample(etExample) > 0) {
            return DataResult.build9250("设备组编码重复，修改失败");
        }
        EquipmentTree et = equipmentTreeMapper.selectByPrimaryKey(id);
        et.setName(name);
        et.setCode(code);
        et.setEmType(emType);
        equipmentTreeMapper.updateByPrimaryKeySelective(et);
        return DataResult.build9100();
    }

    @Override
    public DataResult deleteEquipmentTreeGroupInfo(LoginInfo li, long id) throws Exception {
        EquipmentInfoExample eiExample = new EquipmentInfoExample();
        EquipmentInfoExample.Criteria eiCriteria = eiExample.createCriteria();
        eiCriteria.andEmTreeEqualTo(id);
        List<EquipmentInfo> eiList = equipmentInfoMapper.selectByExample(eiExample);
        if (eiList.size() > 0) {
            return DataResult.build9250("该设备组下存在设备，无法删除");
        }

        EquipmentTree newEt = new EquipmentTree();
        newEt.setId(id);
        newEt.setIsDelete(1);
        equipmentTreeMapper.updateByPrimaryKeySelective(newEt);

        return DataResult.build9100();
    }

    @Override
    public DataResult selectEquipment(LoginInfo li, int pageNum, int pageSize, String subsystemId, String emGrade, String emState, String subTreeId,String emName) throws Exception {
        EquipmentInfoExample eiExample = new EquipmentInfoExample();
        EquipmentInfoExample.Criteria eiCriteria = eiExample.createCriteria();
        if (StrUtil.isNotBlank(subsystemId)) {
            long treeId = Long.parseLong(subsystemId);
            List<Long> treeIdList = new ArrayList<>();
            treeIdList.add(treeId);
            EquipmentTreeExample etExample = new EquipmentTreeExample();
            etExample.createCriteria().andBaseIdEqualTo(treeId);
            List<EquipmentTree> etList = equipmentTreeMapper.selectByExample(etExample);
            for (EquipmentTree et : etList) {
                treeIdList.add(et.getId());
            }
            eiCriteria.andEmTreeIn(treeIdList);
        }
        if (StrUtil.isNotBlank(emName)) {
            eiCriteria.andEmNameLike("%" + emName + "%");
        }
        if (StrUtil.isNotBlank(emGrade)) {
            eiCriteria.andEmGradeEqualTo(Integer.parseInt(emGrade));
        }
        if (StrUtil.isNotBlank(emState)) {
            eiCriteria.andEmStateEqualTo(Integer.parseInt(emState));
        }
        if (StrUtil.isNotBlank(subTreeId)) {
            eiCriteria.andSubTreeIdEqualTo(Long.parseLong(subTreeId));
        }
        eiCriteria.andIsDeleteEqualTo(0);
        eiExample.setOrderByClause("create_time desc");
        Page<EquipmentInfo> page = PageHelper.startPage(pageNum, pageSize);
        List<EquipmentInfo> eiList = equipmentInfoMapper.selectByExample(eiExample);
        List<Map<String, Object>> list = new ArrayList<>();
        for (EquipmentInfo ei : eiList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", ei.getId());
            map.put("emName", ei.getEmName());
            map.put("emCode", ei.getEmCode());
            map.put("archiveCode", ei.getArchiveCode());
            map.put("assetCode", ei.getAssetCode());
            map.put("dataCode", ei.getDataCode());
            map.put("factoryCode", ei.getFactoryCode());
            map.put("emGrade", ei.getEmGrade());
            map.put("emSpecification", ei.getEmSpecification());
            map.put("mainParameter", ei.getMainParameter());
            map.put("emLocation", ei.getEmLocation());
            map.put("emTreeId", ei.getEmTree());
            map.put("manufacturer", ei.getManufacturer());
            map.put("isProvide", ei.getIsProvide());
            map.put("isSpecial", ei.getIsSpecial());

            map.put("emType", ei.getEmType());
            map.put("emState", ei.getEmState());
            map.put("unit", ei.getUnit());
            map.put("operationTime", DateUtil.formatDate(ei.getOperationTime()));
            map.put("purchaseTime", DateUtil.formatDate(ei.getPurchaseTime()));
            map.put("factoryTime", DateUtil.formatDate(ei.getFactoryTime()));

            map.put("specialNextTime", (ei.getSpecialNextTime() == null || ei.getIsSpecial() == 0) ? "" : DateUtil.formatDate(ei.getSpecialNextTime()));
            map.put("isScrap", ei.getIsScrap());
            map.put("isElectrical", ei.getIsElectrical());
            list.add(map);
        }
        return DataResult.build9100(new GridData(page.getTotal(), list));
    }

    @Override
    public DataResult selectEquipmentInfo(LoginInfo li, long id) throws Exception {
        EquipmentInfo ei = equipmentInfoMapper.selectByPrimaryKey(id);
        if (ei == null || ei.getIsDelete() == 1) {
            return DataResult.build9404();
        }

        EquipmentTree et = equipmentTreeMapper.selectByPrimaryKey(ei.getEmTree());
        long emTreeSubsystemId;
        long emTreeGroupId = 0L;
        if (et.getType() == 2) { // 在子系统下
            emTreeSubsystemId = et.getId();
        } else {
            emTreeSubsystemId = et.getBaseId();
            emTreeGroupId = et.getId();
        }
        EquipmentTreeExample etExample = new EquipmentTreeExample();
        etExample.createCriteria().andIsDeleteEqualTo(0);
        List<EquipmentTree> etList = equipmentTreeMapper.selectByExample(etExample);
        List<String> nodeStr = equipmentTreeService.reverseSelectNode(etList, ei.getEmTree());


        BusinessFileExample bfExample = new BusinessFileExample();
        BusinessFileExample.Criteria bfCriteria = bfExample.createCriteria();
        bfCriteria.andBusTablesIdEqualTo(ei.getId());
        bfCriteria.andBusTypeEqualTo(2);
        bfCriteria.andFileGroupEqualTo(1);
        bfCriteria.andFileTypeEqualTo(1);
        List<BusinessFile> bfList = businessFileMapper.selectByExample(bfExample);

        String fileCode = bfList.stream().max(Comparator.comparing(BusinessFile::getCreateTime)).map(BusinessFile::getFileCode).orElse(null);

        Map<String, Object> map = new HashMap<>();
        map.put("id", ei.getId());
        map.put("emName", ei.getEmName());
        map.put("emCode", ei.getEmCode());
        map.put("archiveCode", ei.getArchiveCode());
        map.put("assetCode", ei.getAssetCode());
        map.put("dataCode", ei.getDataCode());
        map.put("factoryCode", ei.getFactoryCode());
        map.put("emGrade", ei.getEmGrade());
        map.put("emSpecification", ei.getEmSpecification());
        map.put("mainParameter", ei.getMainParameter());
        map.put("emLocation", ei.getEmLocation());
        map.put("emTreeId", ei.getEmTree());

        map.put("emTreeSubsystemId", emTreeSubsystemId);
        map.put("emTreeGroupId", emTreeGroupId);

        map.put("emType", ei.getEmType());
        map.put("emState", ei.getEmState());
        map.put("manufacturer", ei.getManufacturer());
        map.put("unit", ei.getUnit());
        map.put("operationTime", DateUtil.formatDate(ei.getOperationTime()));
        map.put("purchaseTime", DateUtil.formatDate(ei.getPurchaseTime()));
        map.put("factoryTime", DateUtil.formatDate(ei.getFactoryTime()));
        map.put("isProvide", ei.getIsProvide());
        map.put("isSpecial", ei.getIsSpecial());
        map.put("specialNextTime", (ei.getSpecialNextTime() == null || ei.getIsSpecial() == 0) ? "" : DateUtil.formatDate(ei.getSpecialNextTime()));
        map.put("isScrap", ei.getIsScrap());
        map.put("isElectrical", ei.getIsElectrical());
        map.put("deviceClassify", ei.getDeviceClassify());
        map.put("area",String.join("/", nodeStr));
        map.put("equipmentImg", fileCode);

        return DataResult.build9100(map);
    }

    @Override
    public DataResult insertEquipmentInfo(LoginInfo li, EquipmentDto dto) throws Exception {
        EquipmentInfoExample eiExample = new EquipmentInfoExample();
        eiExample.createCriteria().andEmCodeEqualTo(dto.getEmCode());
        if (equipmentInfoMapper.countByExample(eiExample) > 0) {
            return DataResult.build9250("设备编号重复");
        }
        EquipmentTree equipmentTree = equipmentTreeMapper.selectByPrimaryKey(Long.parseLong(dto.getEmTreeId()));

        EquipmentInfo newEi = new EquipmentInfo();
        if (equipmentTree.getType() == 3) {
            newEi.setSubTreeId(equipmentTree.getBaseId());
        } else {
            newEi.setSubTreeId(equipmentTree.getId());
        }
        newEi.setEmName(dto.getEmName());
        newEi.setEmCode(dto.getEmCode());
        newEi.setArchiveCode(StrUtil.isBlank(dto.getArchiveCode()) ? "" : dto.getArchiveCode());
        newEi.setAssetCode(StrUtil.isBlank(dto.getAssetCode()) ? "" : dto.getAssetCode());
        newEi.setDataCode(StrUtil.isBlank(dto.getDataCode()) ? "" : dto.getDataCode());
        newEi.setFactoryCode(StrUtil.isBlank(dto.getFactoryCode()) ? "" : dto.getFactoryCode());
        newEi.setEmGrade(Integer.parseInt(dto.getEmGrade()));
        newEi.setEmSpecification(StrUtil.isBlank(dto.getEmSpecification()) ? "" : dto.getEmSpecification());
        newEi.setMainParameter(StrUtil.isBlank(dto.getMainParameter()) ? "" : dto.getMainParameter());
        newEi.setEmTree(Long.parseLong(dto.getEmTreeId()));
        newEi.setEmType(Integer.parseInt(dto.getEmType()));
        newEi.setEmLocation(StrUtil.isBlank(dto.getEmLocation()) ? "" : dto.getEmLocation());
        newEi.setEmState(Integer.parseInt(dto.getEmState()));
        newEi.setManufacturer(StrUtil.isBlank(dto.getManufacturer()) ? "" : dto.getManufacturer());
        newEi.setEmDesc("");
        newEi.setUnit(StrUtil.isBlank(dto.getUnit()) ? "" : dto.getUnit());
        newEi.setOperationTime(StrUtil.isBlank(dto.getOperationTime()) ? null :DateUtil.parseDate(dto.getOperationTime()));
        newEi.setPurchaseTime(StrUtil.isBlank(dto.getPurchaseTime()) ? null :DateUtil.parseDate(dto.getPurchaseTime()));
        newEi.setFactoryTime(StrUtil.isBlank(dto.getFactoryTime()) ? null :DateUtil.parseDate(dto.getFactoryTime()));
        newEi.setIsProvide(Integer.parseInt(dto.getIsProvide()));
        newEi.setIsSpecial(Integer.parseInt(dto.getIsSpecial()));
        newEi.setSpecialNextTime(StrUtil.isBlank(dto.getSpecialNextTime()) ? null : DateUtil.parseDate(dto.getSpecialNextTime()));
        newEi.setIsScrap(Integer.parseInt(dto.getIsScrap()));
        newEi.setIsElectrical(Integer.parseInt(dto.getIsElectrical()));
        newEi.setIsDelete(0);
        newEi.setCreateTime(new Date());
        newEi.setAuxiliaryInfo("");
        newEi.setDeviceClassify(StrUtil.isBlank(dto.getDeviceClassify()) ? "" : dto.getDeviceClassify());
        equipmentInfoMapper.insert(newEi);

        commonService.insertEquipmentOperationLog(newEi.getId(), li.getLoginEmployeeId(), "新增设备");
        return DataResult.build9100(newEi.getId());
    }

    @Override
    public DataResult updateEquipmentInfo(LoginInfo li, EquipmentDto dto) throws Exception {
        EquipmentInfoExample eiExample = new EquipmentInfoExample();
        eiExample.createCriteria().andEmCodeEqualTo(dto.getEmCode()).andIdNotEqualTo(Long.parseLong(dto.getId()));
        if (equipmentInfoMapper.countByExample(eiExample) > 0) {
            return DataResult.build9250("设备编号重复");
        }
        EquipmentTree equipmentTree = equipmentTreeMapper.selectByPrimaryKey(Long.parseLong(dto.getEmTreeId()));
        EquipmentInfo ei = equipmentInfoMapper.selectByPrimaryKey(Long.parseLong(dto.getId()));
        String OldLocation = ei.getEmLocation();
        if (equipmentTree.getType() == 3) {
            ei.setSubTreeId(equipmentTree.getBaseId());
        } else {
            ei.setSubTreeId(equipmentTree.getId());
        }
        ei.setEmName(dto.getEmName());
        ei.setEmCode(dto.getEmCode());
        ei.setArchiveCode(StrUtil.isBlank(dto.getArchiveCode()) ? "" : dto.getArchiveCode());
        ei.setAssetCode(StrUtil.isBlank(dto.getAssetCode()) ? "" : dto.getAssetCode());
        ei.setDataCode(StrUtil.isBlank(dto.getDataCode()) ? "" : dto.getDataCode());
        ei.setFactoryCode(StrUtil.isBlank(dto.getFactoryCode()) ? "" : dto.getFactoryCode());
        ei.setEmGrade(Integer.parseInt(dto.getEmGrade()));
        ei.setEmSpecification(StrUtil.isBlank(dto.getEmSpecification()) ? "" : dto.getEmSpecification());
        ei.setManufacturer(StrUtil.isBlank(dto.getManufacturer()) ? "" : dto.getManufacturer());
        ei.setMainParameter(StrUtil.isBlank(dto.getMainParameter()) ? "" : dto.getMainParameter());
        ei.setEmTree(Long.parseLong(dto.getEmTreeId()));
        ei.setEmType(Integer.parseInt(dto.getEmType()));
        ei.setEmLocation(StrUtil.isBlank(dto.getEmLocation()) ? "" : dto.getEmLocation());
        ei.setEmState(Integer.parseInt(dto.getEmState()));
        ei.setUnit(StrUtil.isBlank(dto.getUnit()) ? "" : dto.getUnit());
        ei.setOperationTime(StrUtil.isBlank(dto.getOperationTime()) ? null :DateUtil.parseDate(dto.getOperationTime()));
        ei.setPurchaseTime(StrUtil.isBlank(dto.getPurchaseTime()) ? null :DateUtil.parseDate(dto.getPurchaseTime()));
        ei.setFactoryTime(StrUtil.isBlank(dto.getFactoryTime()) ? null :DateUtil.parseDate(dto.getFactoryTime()));
        ei.setIsProvide(Integer.parseInt(dto.getIsProvide()));
        ei.setIsSpecial(Integer.parseInt(dto.getIsSpecial()));
        ei.setSpecialNextTime(StrUtil.isBlank(dto.getSpecialNextTime()) ? null : DateUtil.parseDate(dto.getSpecialNextTime()));
        ei.setIsScrap(Integer.parseInt(dto.getIsScrap()));
        ei.setIsElectrical(Integer.parseInt(dto.getIsElectrical()));
        ei.setDeviceClassify(StrUtil.isBlank(dto.getDeviceClassify()) ? "" : dto.getDeviceClassify());
        equipmentInfoMapper.updateByPrimaryKey(ei);
        if (!OldLocation.equals(ei.getEmLocation())) {
            EquipmentMoveLog newEml = new EquipmentMoveLog();
            newEml.setEmId(Long.parseLong(dto.getId()));
            newEml.setOldLocation(OldLocation);
            newEml.setNewLocation(dto.getEmLocation());
            newEml.setEmployeeId(li.getLoginEmployeeId());
            newEml.setMoveTime(new Date());
            equipmentMoveLogMapper.insert(newEml);
            commonService.insertEquipmentOperationLog(Long.parseLong(dto.getId()), li.getLoginEmployeeId(), "移动设备");
        }
        commonService.insertEquipmentOperationLog(Long.parseLong(dto.getId()), li.getLoginEmployeeId(), "修改设备");
        return DataResult.build9100();
    }

    @Override
    public DataResult updateEquipmentInfoOfScrap(LoginInfo li, long id) throws Exception {
        EquipmentInfo newEi = new EquipmentInfo();
        newEi.setId(id);
        newEi.setIsScrap(1);
        equipmentInfoMapper.updateByPrimaryKeySelective(newEi);
        commonService.insertEquipmentOperationLog(id, li.getLoginEmployeeId(), "报废设备");
        return DataResult.build9100();
    }

    @Override
    public DataResult deleteEquipmentInfo(LoginInfo li, long id) throws Exception {
        EquipmentInfo newEi = new EquipmentInfo();
        newEi.setId(id);
        newEi.setIsDelete(1);
        equipmentInfoMapper.updateByPrimaryKeySelective(newEi);
        commonService.insertEquipmentOperationLog(id, li.getLoginEmployeeId(), "删除设备");
        return DataResult.build9100();
    }

    @Override
    public DataResult selectEquipmentData(LoginInfo li, long id) throws Exception {
        EquipmentInfo ei = equipmentInfoMapper.selectByPrimaryKey(id);

        List<String> emFileCodeList = new ArrayList<>();
        BusinessFileExample bfExample = new BusinessFileExample();
        BusinessFileExample.Criteria bfCriteria = bfExample.createCriteria();
        bfCriteria.andBusTablesIdEqualTo(ei.getId());
        bfCriteria.andBusTypeEqualTo(2);
        bfCriteria.andFileGroupEqualTo(1);
        bfCriteria.andFileTypeEqualTo(1);
        List<BusinessFile> bfList = businessFileMapper.selectByExample(bfExample);
        for (BusinessFile bf : bfList) {
            emFileCodeList.add(bf.getFileCode());
        }

        Map<String, Object> map = new HashMap<>();
        map.put("emDesc", ei.getEmDesc());
        map.put("emFileCodes", emFileCodeList);
        return DataResult.build9100(map);
    }

    @Override
    public DataResult updateEquipmentData(LoginInfo li, long id, String emDesc, String emFileCodes) throws Exception {
        EquipmentInfo newEi = new EquipmentInfo();
        newEi.setId(id);
        newEi.setEmDesc(StrUtil.isBlank(emDesc) ? "" : emDesc);
        equipmentInfoMapper.updateByPrimaryKeySelective(newEi);

        BusinessFileExample bfExample = new BusinessFileExample();
        BusinessFileExample.Criteria bfCriteria = bfExample.createCriteria();
        bfCriteria.andBusTablesIdEqualTo(id);
        bfCriteria.andBusTypeEqualTo(2);
        bfCriteria.andFileGroupEqualTo(1);
        bfCriteria.andFileTypeEqualTo(1);
        businessFileMapper.deleteByExample(bfExample);

        if (StrUtil.isNotBlank(emFileCodes)) {
            Date date = new Date();
            for (String fileCode : emFileCodes.split(",")) {
                BusinessFile newBf = new BusinessFile();
                newBf.setBusTablesId(id);
                newBf.setBusType(2);
                newBf.setFileGroup(1);
                newBf.setFileCode(fileCode);
                newBf.setFileType(1);
                newBf.setEmployeeId(li.getLoginEmployeeId());
                newBf.setUpdateTime(date);
                newBf.setCreateTime(date);
                businessFileMapper.insert(newBf);
            }
        }
        return DataResult.build9100();
    }

    @Override
    public DataResult selectEquipmentDocument(LoginInfo li, int pageNum, int pageSize, long id, int type) throws Exception {
        SystemEmployeeExample seExample = new SystemEmployeeExample();
        seExample.createCriteria().andIsDeleteEqualTo(0);
        List<SystemEmployee> seList1 = systemEmployeeMapper.selectByExample(seExample);
        Map<Long, String> seMap = new HashMap<>();
        for (SystemEmployee se : seList1) {
            seMap.put(se.getId(), se.getEmployeeName());
        }

        BusinessFileExample bfExample = new BusinessFileExample();
        BusinessFileExample.Criteria bfCriteria = bfExample.createCriteria();
        bfCriteria.andBusTablesIdEqualTo(id);
        bfCriteria.andBusTypeEqualTo(2);
        bfCriteria.andFileGroupEqualTo(type);
        bfCriteria.andFileTypeEqualTo(4);
        bfExample.setOrderByClause("create_time");
        Page<BusinessFile> page = PageHelper.startPage(pageNum, pageSize);
        List<BusinessFile> bfList = businessFileMapper.selectByExample(bfExample);
        List<Map<String, Object>> list = new ArrayList<>();
        for (BusinessFile bf : bfList) {
            SystemFile sf = systemFileMapper.selectByPrimaryKey(bf.getFileCode());
            Map<String, Object> map = new HashMap<>();
            map.put("id", bf.getId());
            map.put("fileCode", bf.getFileCode());
            map.put("fileName", sf == null ? "" : sf.getFileName());
            map.put("employeeName", seMap.get(bf.getEmployeeId()));
            map.put("createTime", DateUtil.formatDateTime(bf.getCreateTime()));
            list.add(map);
        }
        return DataResult.build9100(new GridData(page.getTotal(), list));
    }

    @Override
    public DataResult insertEquipmentDocument(LoginInfo li, long id, int type, String fileCodes) throws Exception {
        if (StrUtil.isNotBlank(fileCodes)) {
            Date date = new Date();
            for (String fileCode : fileCodes.split(",")) {
                BusinessFile newBf = new BusinessFile();
                newBf.setBusTablesId(id);
                newBf.setBusType(2);
                newBf.setFileGroup(type);
                newBf.setFileCode(fileCode);
                newBf.setFileType(4);
                newBf.setEmployeeId(li.getLoginEmployeeId());
                newBf.setUpdateTime(date);
                newBf.setCreateTime(date);
                businessFileMapper.insert(newBf);
            }
        }
        commonService.insertEquipmentOperationLog(id, li.getLoginEmployeeId(), "新增设备文档");
        return DataResult.build9100();
    }


    @Override
    public DataResult deleteEquipmentDocument(LoginInfo li, long id) throws Exception {
        BusinessFile bf = businessFileMapper.selectByPrimaryKey(id);
        fileService.deleteFile(li, bf.getFileCode());
        businessFileMapper.deleteByPrimaryKey(bf.getId());
        commonService.insertEquipmentOperationLog(bf.getBusTablesId(), li.getLoginEmployeeId(), "删除设备文档");
        return DataResult.build9100();
    }

    @Override
    public DataResult selectEquipmentOperationLog(LoginInfo li, int pageNum, int pageSize, long id) throws Exception {
        SystemEmployeeExample seExample = new SystemEmployeeExample();
        seExample.createCriteria().andIsDeleteEqualTo(0);
        List<SystemEmployee> seList = systemEmployeeMapper.selectByExample(seExample);
        Map<Long, String> seMap = new HashMap<>();
        for (SystemEmployee se : seList) {
            seMap.put(se.getId(), se.getEmployeeName());
        }

        EquipmentOperationLogExample eolExample = new EquipmentOperationLogExample();
        eolExample.createCriteria().andEmIdEqualTo(id);
        eolExample.setOrderByClause("operation_time desc");
        Page<EquipmentOperationLog> page = PageHelper.startPage(pageNum, pageSize);
        List<EquipmentOperationLog> eolList = equipmentOperationLogMapper.selectByExample(eolExample);
        List<Map<String, Object>> list = new ArrayList<>();
        for (EquipmentOperationLog eol : eolList) {
            Map<String, Object> map = new HashMap<>();
            map.put("operation", eol.getOperation());
            map.put("employeeName", seMap.get(eol.getEmployeeId()));
            map.put("operationTime", DateUtil.formatDateTime(eol.getOperationTime()));
            list.add(map);
        }
        return DataResult.build9100(new GridData(page.getTotal(), list));
    }

    @Override
    public DataResult selectEquipmentMoveLog(LoginInfo li, int pageNum, int pageSize, long id) throws Exception {
        SystemEmployeeExample seExample = new SystemEmployeeExample();
        seExample.createCriteria().andIsDeleteEqualTo(0);
        List<SystemEmployee> seList = systemEmployeeMapper.selectByExample(seExample);
        Map<Long, String> seMap = new HashMap<>();
        for (SystemEmployee se : seList) {
            seMap.put(se.getId(), se.getEmployeeName());
        }

        EquipmentMoveLogExample emlExample = new EquipmentMoveLogExample();
        emlExample.createCriteria().andEmIdEqualTo(id);
        emlExample.setOrderByClause("move_time desc");
        Page<EquipmentMoveLog> page = PageHelper.startPage(pageNum, pageSize);
        List<EquipmentMoveLog> emlList = equipmentMoveLogMapper.selectByExample(emlExample);
        List<Map<String, Object>> list = new ArrayList<>();
        for (EquipmentMoveLog eml : emlList) {
            Map<String, Object> map = new HashMap<>();
            map.put("oldLocation", eml.getOldLocation());
            map.put("newLocation", eml.getNewLocation());
            map.put("employeeName", seMap.get(eml.getEmployeeId()));
            map.put("moveTime", DateUtil.formatDateTime(eml.getMoveTime()));
            list.add(map);
        }
        return DataResult.build9100(new GridData(page.getTotal(), list));
    }

    @Override
    public DataResult selectEquipmentPlc(LoginInfo li, long id) throws Exception {
        Map<Integer, String> typeMap = commonService.getDictMap("TYPE_EM_PLC_TYPE");
        EquipmentPlcConfigExample epcExample = new EquipmentPlcConfigExample();
        EquipmentPlcConfigExample.Criteria epcCriteria = epcExample.createCriteria();
        epcCriteria.andEmIdEqualTo(id);
        epcExample.setOrderByClause("create_time");
        List<EquipmentPlcConfig> epcList = equipmentPlcConfigMapper.selectByExample(epcExample);
        List<Map<String, Object>> list = new ArrayList<>();
        for (EquipmentPlcConfig epc : epcList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", epc.getId());
            map.put("type", epc.getType());
            map.put("unit", epc.getUnit());
            map.put("typeName", typeMap.get(epc.getType()));
            map.put("upperLimit", epc.getUpperLimit());
            map.put("lowerLimit", epc.getLowerLimit());
            list.add(map);
        }
        return DataResult.build9100(list);
    }

    @Override
    public DataResult insertEquipmentPlc(LoginInfo li, long emId, int type, String unit, String upperLimit, String lowerLimit) throws Exception {
        Date date = new Date();
        EquipmentPlcConfig newEpc = new EquipmentPlcConfig();
        newEpc.setEmId(emId);
        newEpc.setType(type);
        newEpc.setUnit(unit);
        newEpc.setUpperLimit(upperLimit);
        newEpc.setLowerLimit(lowerLimit);
        newEpc.setUpdateTime(date);
        newEpc.setCreateTime(date);
        equipmentPlcConfigMapper.insert(newEpc);
        commonService.insertEquipmentOperationLog(emId, li.getLoginEmployeeId(), "新增设备PLC配置");
        return DataResult.build9100();
    }

    @Override
    public DataResult updateEquipmentPlc(LoginInfo li, long id, int type, String unit, String upperLimit, String lowerLimit) throws Exception {
        Date date = new Date();
        EquipmentPlcConfig epc = equipmentPlcConfigMapper.selectByPrimaryKey(id);
        EquipmentPlcConfig newEpc = new EquipmentPlcConfig();
        newEpc.setId(id);
        newEpc.setType(type);
        newEpc.setUnit(unit);
        newEpc.setUpperLimit(upperLimit);
        newEpc.setLowerLimit(lowerLimit);
        newEpc.setUpdateTime(date);
        equipmentPlcConfigMapper.updateByPrimaryKeySelective(newEpc);
        commonService.insertEquipmentOperationLog(epc.getEmId(), li.getLoginEmployeeId(), "修改设备PLC配置");
        return DataResult.build9100();
    }

    @Override
    public DataResult deleteEquipmentPlc(LoginInfo li, long id) throws Exception {
        EquipmentPlcConfig epc = equipmentPlcConfigMapper.selectByPrimaryKey(id);
        equipmentPlcConfigMapper.deleteByPrimaryKey(id);
        commonService.insertEquipmentOperationLog(epc.getEmId(), li.getLoginEmployeeId(), "修改设备PLC配置");
        return DataResult.build9100();
    }

    @Override
    public DataResult selectEquipmentUpkeep(LoginInfo li, int pageNum, int pageSize, long id) throws Exception {
        UpkeepWorkOrderExample uwoExample = new UpkeepWorkOrderExample();
        uwoExample.createCriteria().andEmIdEqualTo(id).andUpkeepStateGreaterThanOrEqualTo(3);
        uwoExample.setOrderByClause("upkeep_start_time desc");
        Page<SystemUser> page = PageHelper.startPage(pageNum, pageSize);
        List<UpkeepWorkOrder> uwoList = upkeepWorkOrderMapper.selectByExample(uwoExample);
        Map<Long, List<UpkeepTask>> upkeepTaskMap = MapUtil.newHashMap();
        Map<Long, UpkeepMaintenance> upkeepMaintenanceMap = MapUtil.newHashMap();
        if (CollUtil.isNotEmpty(uwoList)) {
            // 任务
            List<Long> upkeepIdList = uwoList.stream().map(UpkeepWorkOrder::getUpkeepId).collect(Collectors.toList());
            UpkeepTaskExample upkeepTaskExample = new UpkeepTaskExample();
            upkeepTaskExample.createCriteria().andUpkeepIdIn(upkeepIdList);
            List<UpkeepTask> upkeepTasks = upkeepTaskMapper.selectByExample(upkeepTaskExample);
            upkeepTaskMap = upkeepTasks.stream().collect(Collectors.groupingBy(UpkeepTask::getUpkeepId));
            // 说明
            UpkeepMaintenanceExample upkeepMaintenanceExample = new UpkeepMaintenanceExample();
            upkeepMaintenanceExample.createCriteria().andUpkeepIdIn(upkeepIdList).andMtcStateNotEqualTo(1);
            List<UpkeepMaintenance> upkeepMaintenances = upkeepMaintenanceMapper.selectByExample(upkeepMaintenanceExample);
            // 根据 k 进行分组，并获取每组中最大创建时间的记录
            upkeepMaintenanceMap = upkeepMaintenances.stream()
                    .collect(Collectors.toMap(
                            UpkeepMaintenance::getUpkeepId, // 分组的键
                            upkeep -> upkeep, // 分组的值
                            (upkeep1, upkeep2) -> upkeep1.getCreateTime().after(upkeep2.getCreateTime()) ? upkeep1 : upkeep2 // 选择最大创建时间的记录
                    ));
        }

        List<Map<String, Object>> list = new ArrayList<>();
        for (UpkeepWorkOrder uwo : uwoList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", uwo.getUpkeepId());
            map.put("code", uwo.getWorkOrderCode());
            if(uwo.getUpkeepStartTime() != null){
                map.put("time", DateUtil.formatDateTime(uwo.getUpkeepStartTime()));
            }else {
                map.put("time", uwo.getUpkeepStartTime());
            }
            map.put("employeeName", SystemData.employeeMap.get(uwo.getEmployeeId()) == null ? "" : SystemData.employeeMap.get(uwo.getEmployeeId()).getEmployeeName());
            map.put("state", uwo.getUpkeepState());
            map.put("taskNameList", upkeepTaskMap.getOrDefault(uwo.getUpkeepId(), CollUtil.newArrayList()));

            List<Integer> notInStatus = Arrays.asList(EnumRepState.INVALID.getRepState(), EnumRepState.PENDING_ANNOUNCE.getRepState(),
                    EnumRepState.PENDING_RECEIVE.getRepState(),
                    EnumRepState.PENDING_REFUSE.getRepState(),
                    EnumRepState.PENDING_TRANSFER.getRepState());
            UpkeepMaintenanceExample keepMainExample = new UpkeepMaintenanceExample();
            UpkeepMaintenanceExample.Criteria keepMainCriteria = keepMainExample.createCriteria();
            keepMainCriteria.andUpkeepIdEqualTo(uwo.getUpkeepId());
            keepMainCriteria.andMtcStateNotIn(notInStatus);
            keepMainExample.setOrderByClause("create_time desc limit 1");
            List<UpkeepMaintenance> upkeepMaintenanceList = upkeepMaintenanceMapper.selectByExample(keepMainExample);

            UpkeepMaintenance upkeepMaintenance = upkeepMaintenanceList.get(0);
            getMaintenanceFileList(map, upkeepMaintenance.getId());
            map.put("deviceLocationAndLocationName", uwo.getEmName()+"-"+uwo.getEmLocation());
            String remark = Optional.ofNullable(upkeepMaintenanceMap.getOrDefault(uwo.getUpkeepId(), null))
                    .map(UpkeepMaintenance::getRemark)
                    .orElse("");
            map.put("remark", remark);
            list.add(map);
        }
        return DataResult.build9100(new GridData(page.getTotal(), list));
    }

    @Override
    public DataResult selectEquipmentPatrol(LoginInfo li, int pageNum, int pageSize, long id) throws Exception {
        EquipmentInfo ei = equipmentInfoMapper.selectByPrimaryKey(id);

        PatrolWorkOrderExample pwoExample = new PatrolWorkOrderExample();
        pwoExample.createCriteria().andTreeIdEqualTo(ei.getEmTree()).andStateGreaterThanOrEqualTo(2);
        pwoExample.setOrderByClause("start_time desc");
        Page<SystemUser> page = PageHelper.startPage(pageNum, pageSize);
        List<PatrolWorkOrder> pwoList = patrolWorkOrderMapper.selectByExample(pwoExample);

        List<Map<String, Object>> list = new ArrayList<>();
        for (PatrolWorkOrder pwo : pwoList) {
            SystemEmployee se = SystemData.employeeMap.get(pwo.getPatrolEmployeeId());
            Map<String, Object> map = new HashMap<>();
            map.put("id", pwo.getId());
            map.put("code", pwo.getCode());
            map.put("time", DateUtil.formatDateTime(pwo.getStartTime()));
            map.put("employeeName", se == null ? "" : se.getEmployeeName());
            map.put("state", pwo.getState());
            map.put("isException", pwo.getIsException());
            map.put("orderException", pwo.getOrderException());
            map.put("endTime", pwo.getEndTime() == null ? null : DateUtil.formatDateTime(pwo.getEndTime()));
            map.put("deviceLocationAndLocationName", ei.getEmName()+"-"+ei.getEmLocation());

            List<Map<String, String>> filePicCode = new ArrayList<>();
            List<Map<String, String>> fileVideoCode = new ArrayList<>();

            BusinessFileExample bfExample = new BusinessFileExample();
            bfExample.createCriteria().andBusTypeEqualTo(8).andFileGroupEqualTo(1).andBusTablesIdEqualTo(pwo.getId());
            List<BusinessFile> bfList = businessFileMapper.selectByExample(bfExample);

            if (bfList.size() > 0) {
                SystemFileExample sfExample = new SystemFileExample();
                sfExample.createCriteria().andFileCodeIn(CollStreamUtil.toList(bfList, BusinessFile::getFileCode));
                List<SystemFile> systemFiles1 = systemFileMapper.selectByExample(sfExample);
                Map<String, SystemFile> fileMap1 = CollStreamUtil.toIdentityMap(systemFiles1, SystemFile::getFileCode);

                for (BusinessFile bf : bfList) {
                    Map<String, String> fileMap = new HashMap<>();
                    fileMap.put("fileCode", bf.getFileCode());
                    fileMap.put("fileName", fileMap1.get(bf.getFileCode()).getFileName());
                    if (bf.getFileType() == 1) {
                        filePicCode.add(fileMap);
                    }  else if (bf.getFileType() == 3) {
                        fileVideoCode.add(fileMap);
                    }
                }
            }

            map.put("filePicCode", filePicCode);
            map.put("fileVideoCode", fileVideoCode);


            list.add(map);
        }
        return DataResult.build9100(new GridData(page.getTotal(), list));
    }

    @Override
    public DataResult selectEquipmentPatrolByEmId(LoginInfo li, int pageNum, int pageSize, long id) throws Exception {
        EquipmentInfo ei = equipmentInfoMapper.selectByPrimaryKey(id);

        if (ObjectUtil.isEmpty(ei.getEmType()) || ObjectUtil.equals(0, ei.getEmType())) {
            return DataResult.build9100(CollUtil.newArrayList());
        }

        PatrolWorkOrderExample pwoExample = new PatrolWorkOrderExample();
        pwoExample.createCriteria().andTreeIdEqualTo(ei.getEmTree()).andStateGreaterThanOrEqualTo(2);
        pwoExample.setOrderByClause("start_time desc");
        Page<SystemUser> page = PageHelper.startPage(pageNum, pageSize);
        List<PatrolWorkOrder> pwoList = patrolWorkOrderMapper.selectByExample(pwoExample);

        List<Map<String, Object>> list = new ArrayList<>();
        for (PatrolWorkOrder pwo : pwoList) {
            SystemEmployee se = SystemData.employeeMap.get(pwo.getPatrolEmployeeId());
            Map<String, Object> map = new HashMap<>();
            map.put("id", pwo.getId());
            map.put("code", pwo.getCode());
            map.put("time", DateUtil.formatDateTime(pwo.getStartTime()));
            map.put("employeeName", se == null ? "" : se.getEmployeeName());
            map.put("state", pwo.getState());
            map.put("isException", pwo.getIsException());
            map.put("orderException", pwo.getOrderException());
            map.put("endTime", pwo.getEndTime() == null ? null : DateUtil.formatDateTime(pwo.getEndTime()));
            map.put("deviceLocationAndLocationName", ei.getEmName()+"-"+ei.getEmLocation());

            List<Map<String, String>> filePicCode = new ArrayList<>();
            List<Map<String, String>> fileVideoCode = new ArrayList<>();

            BusinessFileExample bfExample = new BusinessFileExample();
            bfExample.createCriteria().andBusTypeEqualTo(8).andFileGroupEqualTo(1).andBusTablesIdEqualTo(pwo.getId());
            List<BusinessFile> bfList = businessFileMapper.selectByExample(bfExample);

            if (bfList.size() > 0) {
                SystemFileExample sfExample = new SystemFileExample();
                sfExample.createCriteria().andFileCodeIn(CollStreamUtil.toList(bfList, BusinessFile::getFileCode));
                List<SystemFile> systemFiles1 = systemFileMapper.selectByExample(sfExample);
                Map<String, SystemFile> fileMap1 = CollStreamUtil.toIdentityMap(systemFiles1, SystemFile::getFileCode);

                for (BusinessFile bf : bfList) {
                    Map<String, String> fileMap = new HashMap<>();
                    fileMap.put("fileCode", bf.getFileCode());
                    fileMap.put("fileName", fileMap1.get(bf.getFileCode()).getFileName());
                    if (bf.getFileType() == 1) {
                        filePicCode.add(fileMap);
                    }  else if (bf.getFileType() == 3) {
                        fileVideoCode.add(fileMap);
                    }
                }
            }

            map.put("filePicCode", filePicCode);
            map.put("fileVideoCode", fileVideoCode);


            list.add(map);
        }
        return DataResult.build9100(new GridData(page.getTotal(), list));
    }

    @Override
    public DataResult selectEquipmentAuxiliary(LoginInfo li, long id) throws Exception {
        return DataResult.build9100(equipmentInfoMapper.selectByPrimaryKey(id).getAuxiliaryInfo());
    }

    @Override
    public DataResult insertEquipmentAuxiliary(LoginInfo li, long id, String fileCode) throws Exception {
        EquipmentInfo newEi = new EquipmentInfo();
        newEi.setId(id);
        newEi.setAuxiliaryInfo(fileCode);
        equipmentInfoMapper.updateByPrimaryKeySelective(newEi);
        return DataResult.build9100();
    }

    @Override
    public DataResult selectEquipmentTreeUpkeep(LoginInfo li, long id) throws Exception {
        List<Map<String, Object>> list = new ArrayList<>();
        EquipmentInfoExample eiExample = new EquipmentInfoExample();
        eiExample.createCriteria().andSubTreeIdEqualTo(id);
        eiExample.setOrderByClause("create_time desc");
        List<EquipmentInfo> eiList = equipmentInfoMapper.selectByExample(eiExample);
        for (EquipmentInfo ei : eiList) {
            Map<String, Object> map = new HashMap<>();
            map.put("emId", ei.getId());
            map.put("name", ei.getEmName());
            list.add(map);
        }
        return DataResult.build9100(list);
    }

    @Override
    public DataResult selectEquipmentElectrical(LoginInfo li, long id) throws Exception {
        EquipmentElectricalExample example = new EquipmentElectricalExample();
        example.createCriteria().andEmIdEqualTo(id);
        List<EquipmentElectrical> equipmentElectricals = equipmentElectricalMapper.selectByExample(example);
        List<Map<String, Object>> list = new ArrayList<>();
        for (EquipmentElectrical ee : equipmentElectricals) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", ee.getId());
            map.put("emId", ee.getEmId());
            map.put("name", ee.getName());
            map.put("loadDesc", ee.getLoadDesc());
            map.put("continuingModel", ee.getContinuingModel());
            map.put("instrumentModel", ee.getInstrumentModel());
            map.put("protectionState", ee.getProtectionState());
            map.put("protectionName", ee.getProtectionName());
            map.put("protectionValue", ee.getProtectionValue());
            map.put("ct", ee.getCt());
            map.put("cableModel", ee.getCableModel());
            list.add(map);
        }
        return DataResult.build9100(list);
    }

    @Override
    public DataResult insertEquipmentElectrical(LoginInfo li, EquipmentElectricalDto equipmentElectricalDto) throws Exception {
        EquipmentElectrical ee = new EquipmentElectrical();
        ee.setEmId(Long.parseLong(equipmentElectricalDto.getEmId()));
        ee.setName(equipmentElectricalDto.getName());
        ee.setLoadDesc(equipmentElectricalDto.getLoadDesc());
        ee.setInstrumentModel(equipmentElectricalDto.getInstrumentModel());
        ee.setContinuingModel(equipmentElectricalDto.getContinuingModel());
        ee.setProtectionState(equipmentElectricalDto.getProtectionState());
        ee.setProtectionName(equipmentElectricalDto.getProtectionName());
        ee.setProtectionValue(equipmentElectricalDto.getProtectionValue());
        ee.setCt(equipmentElectricalDto.getCt());
        ee.setCableModel(equipmentElectricalDto.getCableModel());
        ee.setCreateTime(new Date());
        equipmentElectricalMapper.insert(ee);
        return DataResult.build9100();
    }

    @Override
    public DataResult updateEquipmentElectrical(LoginInfo li, EquipmentElectricalDto equipmentElectricalDto) throws Exception {
        if(StrUtil.isBlank(equipmentElectricalDto.getId())){
            return DataResult.build9250("id不能为空");
        }
        EquipmentElectrical ee = new EquipmentElectrical();
        ee.setId(Long.parseLong(equipmentElectricalDto.getId()));
        ee.setEmId(Long.parseLong(equipmentElectricalDto.getEmId()));
        ee.setName(equipmentElectricalDto.getName());
        ee.setLoadDesc(equipmentElectricalDto.getLoadDesc());
        ee.setInstrumentModel(equipmentElectricalDto.getInstrumentModel());
        ee.setContinuingModel(equipmentElectricalDto.getContinuingModel());
        ee.setProtectionState(equipmentElectricalDto.getProtectionState());
        ee.setProtectionName(equipmentElectricalDto.getProtectionName());
        ee.setProtectionValue(equipmentElectricalDto.getProtectionValue());
        ee.setCt(equipmentElectricalDto.getCt());
        ee.setCableModel(equipmentElectricalDto.getCableModel());
        ee.setCreateTime(new Date());
        equipmentElectricalMapper.updateByPrimaryKey(ee);
        return DataResult.build9100();
    }

    @Override
    public DataResult deleteEquipmentElectrical(LoginInfo li, long id) {
        equipmentElectricalMapper.deleteByPrimaryKey(id);
        return DataResult.build9100();
    }

    @Override
    public String regionName(long id) {
        EquipmentTree tree = equipmentTreeMapper.treeName(id);
        StringBuilder nameBuilder = new StringBuilder(tree.getName()); // 使用StringBuilder进行字符串拼接

        long currentBaseId = tree.getBaseId();
        while (currentBaseId != 0) {
            EquipmentTree tree1 = equipmentTreeMapper.treeName(currentBaseId);
            nameBuilder.append("-").append(tree1.getName()); // 拼接新的名称，并添加一个'-'作为分隔符
            currentBaseId = tree1.getBaseId(); // 更新currentBaseId为下一次循环做准备
        }

        return nameBuilder.toString(); // 返回拼接后的完整名称
    }

    @Override
    public DataResult selectDetails(Long id) {
        return null;
    }

    private void getMaintenanceFileList(Map<String, Object> map, Long busTablesId) {
        List<BusinessFileVo> businessFileList = businessFileDao.selectBusinessFileByCodes(busTablesId, EnumBusinessType.UPKEEPMAINTENANCE.getBusType());

        List<Map<String, String>> picOldList = new ArrayList<>();
        List<Map<String, String>> audioOldList = new ArrayList<>();
        List<Map<String, String>> videoOldList = new ArrayList<>();
        List<Map<String, String>> picNewList = new ArrayList<>();
        List<Map<String, String>> audioNewList = new ArrayList<>();
        List<Map<String, String>> videoNewList = new ArrayList<>();
        int i = 1;
        int j = 1;
        for (BusinessFileVo vo : businessFileList) {
            /*
             * FileGroup: 2,维修前的文件，3，维修后的文件
             * fileType： 1,图片pic,2音频audio，3，视频video'
             * */
            if (vo.getFileGroup() == 2) {
                if (1 == vo.getFileType()) {
                    Map<String, String> picOldMap = new HashMap<>();
                    picOldMap.put("fileCode", vo.getFileCode());
                    picOldMap.put("fileName", vo.getFileName());
                    picOldList.add(picOldMap);
                } else if (2 == vo.getFileType()) {
                    Map<String, String> audioOldMap = new HashMap<>();
                    audioOldMap.put("fileCode", vo.getFileCode());
                    if (StrUtil.isBlank(vo.getFileName())) {
                        audioOldMap.put("fileName", "");
                    } else {
                        audioOldMap.put("fileName", "音频" + i + vo.getFileName().substring(vo.getFileName().lastIndexOf(".")));
                    }
                    audioOldList.add(audioOldMap);
                    i++;
                } else if (3 == vo.getFileType()) {
                    Map<String, String> videoOldMap = new HashMap<>();
                    videoOldMap.put("fileCode", vo.getFileCode());
                    videoOldMap.put("fileName", vo.getFileName());
                    videoOldList.add(videoOldMap);
                }
            } else if (vo.getFileGroup() == 3) {
                if (1 == vo.getFileType()) {
                    Map<String, String> picNewMap = new HashMap<>();
                    picNewMap.put("fileCode", vo.getFileCode());
                    picNewMap.put("fileName", vo.getFileName());
                    picNewList.add(picNewMap);
                } else if (2 == vo.getFileType()) {
                    Map<String, String> audioNewMap = new HashMap<>();
                    audioNewMap.put("fileCode", vo.getFileCode());

                    if (StrUtil.isBlank(vo.getFileName())) {
                        audioNewMap.put("fileName", "");
                    } else {
                        audioNewMap.put("fileName", "音频" + j + vo.getFileName().substring(vo.getFileName().lastIndexOf(".")));
                    }
                    audioNewList.add(audioNewMap);
                    j++;
                } else if (3 == vo.getFileType()) {
                    Map<String, String> videoNewMap = new HashMap<>();
                    videoNewMap.put("fileCode", vo.getFileCode());
                    videoNewMap.put("fileName", vo.getFileName());
                    videoNewList.add(videoNewMap);
                }
            }
        }
/*        map.put("picOldList",picOldList);
        map.put("audioOldList",audioOldList);
        map.put("videoOldList",videoOldList);*/
        map.put("picNewList", picNewList);
        map.put("audioNewList", audioNewList);
        map.put("videoNewList", videoNewList);
    }


}
